<template>
  <div class="app-container">
    <div class="card-box">
      <el-table :data="couponReceiveStore.list">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="user.username" label="用户" />
        <el-table-column prop="coupon.name" label="优惠券名称" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="领取时间" />
        <el-table-column prop="used_at" label="使用时间" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="handleDetail(row.id)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-model:page="listQuery.page"
        v-model:limit="listQuery.size"
        :total="couponReceiveStore.totalCount"
        @pagination="fetchData"
      />

      <Detail v-if="currentDetail" v-model="detailVisible" :detail="currentDetail" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useCouponReceiveStoreHook } from "@/store/modules/coupon/receive";
import Pagination from "@/components/Pagination/index.vue";
import Detail from "./components/Detail.vue";
import { CouponReceiveStatus, CouponReceiveType } from "@/api/coupon/receive";

const couponReceiveStore = useCouponReceiveStoreHook();

const listQuery = reactive({
  page: 1,
  size: 20,
});

function statusText(status: CouponReceiveStatus) {
  const map = {
    no_used: "未使用",
    used: "已使用",
    expired: "已过期",
  };
  return map[status] || status;
}

function statusTagType(status: CouponReceiveStatus): any {
  const map = {
    no_used: "success",
    used: "",
    expired: "info",
  };
  return map[status] || "";
}

async function fetchData() {
  await couponReceiveStore.fetchList(listQuery);
}

const detailVisible = ref(false);
const currentDetail = ref<CouponReceiveType | null>(null);

async function handleDetail(id: number) {
  currentDetail.value = await couponReceiveStore.fetchDetail(id);
  detailVisible.value = true;
}

// 在模板中添加Detail组件

onMounted(() => {
  fetchData();
});
</script>
